package cdp.tarasenko.task1;

import java.util.Map;
import java.util.TreeMap;

/**
 * @Author( name = Oleksandr_Tarasenko,
 * date = 26.07.13 )
 */
public class PriorityQueue<T> {
    private TreeMap<Long, T> items = new TreeMap<Long, T>();

    /**
     * Be aware of values with the same priority. If there is value with the priority which is equals
     * to new, it will be replaced with new.
     */
    public void add(T value, Long priority) {
        items.put(priority, value);
    }

    /**
     * Returns and deletes value with minimum priority
     *
     * @return value with minimum priority. Null if queue is empty.
     *
     */
    public T pull() {
        Map.Entry firstEntry = items.firstEntry();
        if (firstEntry == null) return null;
        items.remove(firstEntry.getKey());
        return (T)firstEntry.getValue();
    }

    public T peek() {
        Map.Entry firstEntry = items.firstEntry();
        if (firstEntry == null) return null;
        return (T)firstEntry.getValue();
    }

    public void remove(T value) {
        for (Map.Entry<Long, T> entry : items.entrySet()) {
            if (entry.getValue().equals(value)) {
                items.remove(entry.getKey());
                return;
            }
        }
    }

    public int getSize() {
        return items.size();
    }
}
